import { CascaderSelect } from '@alifd/next';
import { CascaderSelectProps } from '@alifd/next/types/cascader-select';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { getCities, getStations } from './api';

// 0开始 1结束
type direction = '0' | '1';

interface IShuttleStationSelect extends CascaderSelectProps {
  stationOnly?: boolean;
  cityId?: string;
  direction?: direction
}
function RsStationSelect({ stationOnly = false, cityId, direction = '0', ...props }: IShuttleStationSelect) {
  return <RsStationSelectCascade {...props} />;}

function RsStationSelectCascade({ stationOnly = false, direction = '0', ...props }: IShuttleStationSelect) {
  const [data, setData] = useState([]);
  const cities = useRef({}).current;

  useEffect(() => {
    (async function fetchData() {
      const items = await getCities();
      setData(items.map(mapper));
    })();
  }, []);

  const mapper = useCallback((v) => {
    const isStation = !v.itemId;
    const label = v.name;
    const value = isStation ? v.id : v.itemId;
    const item = {
      label,
      value,
      isLeaf: isStation,
      ...v,
    };
    return item;
  }, []);


  const onLoadData = async (v) => {
    const item = cities[v.value];
    if (item.children) return;
    const children = await getStations({ direction, fromCities: [v.itemId] });
    const childrenMap = children?.reduce((acc, cur) => {
      return acc.concat(cur.children)
    }, []);
    item.children = childrenMap.map(mapper);
    setData((prev) => [...prev]);
  };


  return (
    <CascaderSelect
      hasClear
      dataSource={data}
      loadData={onLoadData}
      // style={{ width: '100%' }}
      {...props}
    />
  );
}

export default RsStationSelect;
